package com.vfa.vocaburay;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import com.vfa.data.SettingActivity;
import com.vfa.data.SyncDocs;
import com.vfa.test.QuestionData;
import com.vfa.vocaburay.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import api.wireless.gdata.parser.ParseException;
import api.wireless.gdata.util.ServiceException;

public class ExportQuestionToCsvFile extends Activity {
	
	private static final int DIALOG_AUTHO = 1;
	private static final int DIALOG_RESULT_AUTHO = 2;
	private static final int DIALOG_WAITTING = 3;
	private CheckBox checkbox_Sync;
	private Boolean isCheksync;	
	SyncDocs syncDocs;
	/////////////////////////////////////////////////////
	
	public static QuestionData questionData;
	private Button btnExport;
	ArrayList<String> arrlistlanguage;
	String path;

	ArrayList<String> data;
	
	private TextView viewpath, showstatus, tv;
	private EditText et_Enterfilename;
	String filename;
	String filepath;
	private ProgressBar progress;
	private int myprogress=0;
	private String dialogmessage;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.exportdata_activity);
		questionData = new QuestionData(getApplicationContext());
		data = new ArrayList<String>();
		
		tv = (TextView) findViewById(R.id.textView_ex);
		tv.setText("");
		btnExport = (Button)findViewById(R.id.btn_ExportWord);
		viewpath = (TextView)findViewById(R.id.textView_filepathtoexport);
		showstatus = (TextView)findViewById(R.id.textView_showstatusexport);
		et_Enterfilename = (EditText)findViewById(R.id.editText_enterfilename);
		progress = (ProgressBar)findViewById(R.id.progressBar_export);
		
		checkbox_Sync = (CheckBox)findViewById(R.id.checkBox_Sync_Question_Word);
		
		
		String projectname = "/android/data/com.vfa.vocabulary/";
		
		path = Environment.getExternalStorageDirectory() + projectname;
		
		viewpath.setText(path);
		et_Enterfilename.setText("Questionbackup");
		
		btnExport.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				System.out.println(" isCheksync = " +isCheksync);
				if(isCheksync == true){
					if( TestNetworkConnection.getNetworkStatusNoDialog(getApplicationContext()) == true)
					{
						if(syncDocs.isAuthorize() == true){
							Exportdata();
						}
						else {
								showDialog(DIALOG_AUTHO);
						}
					System.out.println("sysDocs.isAuthorize(); = "+ syncDocs.isAuthorize());
					}
					else{
						Toast.makeText(getApplicationContext(), "Please check your connection ! ", Toast.LENGTH_SHORT).show();
					}
				}
				else {
					Exportdata();
				}
			}
		});
		
		
		checkbox_Sync = (CheckBox)findViewById(R.id.checkBox_Sync_Question_Word);
		syncDocs = new SyncDocs(this);
		LoadSharePreferences();
		
		checkbox_Sync.setOnCheckedChangeListener(onCheck_Sync);
		
	}
	
	
	private void LoadSharePreferences(){
		SharedPreferences sharedPreferences = getSharedPreferences("InsertQuestion", MODE_PRIVATE);
		isCheksync = sharedPreferences.getBoolean(SettingActivity.SYNC, false);
		checkbox_Sync.setChecked(isCheksync);
	}
	
private android.widget.CompoundButton.OnCheckedChangeListener onCheck_Sync = new android.widget.CompoundButton.OnCheckedChangeListener() {
		
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			isCheksync = isChecked;
			
		}
	};
	
	protected Dialog onCreateDialog(int id, Bundle args) {
		 AlertDialog.Builder dialog =new AlertDialog.Builder(this);
			switch (id) {
			
			case DIALOG_AUTHO:
				 LayoutInflater factory = LayoutInflater.from(this);
		            final View textEntryView = factory.inflate(R.layout.login_google, null);
		            dialog.setTitle("Login your account! ");
		            dialog.setView(textEntryView);
		            
		            dialog.setPositiveButton("Login", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int whichButton) {
		            			final EditText etEmail = (EditText) textEntryView.findViewById(R.id.editText_myEmail);
		                    	final EditText etPass = (EditText) textEntryView.findViewById(R.id.editText_myPass);
		                    	final CheckBox cbShowpass = (CheckBox)textEntryView.findViewById(R.id.checkBox_showpassword_login);
		                    	
		                    	String strEmail =  String.valueOf(etEmail.getText()).trim();
		                    	String strPass =  String.valueOf(etPass.getText()).trim();
		                    	
		                    	cbShowpass.setOnCheckedChangeListener(new  CompoundButton.OnCheckedChangeListener() {
									@Override
									public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
										System.out.println("isChecked show pass = "+isChecked );
										
										if (isChecked) {
											etPass.setInputType(InputType.TYPE_CLASS_TEXT);
										} else {
											etPass.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
										}
									}
								});
		                    	
		                        // them catalog
		                    	if(strEmail != "" && strPass!=""){
		                    		if(strEmail.endsWith("@gmail.com")!=true)
		                    		{
		                    			strEmail = strEmail+"@gmail.com";
		                    			System.out.println("email = "+ strEmail);
		                    		}
		                    	if(TestNetworkConnection.getNetworkStatusNoDialog(getApplicationContext())== true){
		                    		try {
		                    			
		                    				syncDocs.Autho(strEmail, strPass);
		                    				if(syncDocs.isAuthorize()==false)
		                    				{
		                    					dialogmessage = "Login fail ! ";
		                    					showDialog(DIALOG_RESULT_AUTHO);
			                    			}
			                    			else{
			                    				Toast.makeText(getApplicationContext(), "Login success ! ", Toast.LENGTH_SHORT).show();
			                    				showstatus.setVisibility(View.VISIBLE);
			                    				showstatus.setText("Login your account success. Click Play to export data to google.");
			                    			}
									} catch (Exception e) {
										dialogmessage = "Login fail ! ";
									}
	                    		}
	                    		else{
	                    			Toast.makeText(getApplicationContext(), "Please check your connection ! ", Toast.LENGTH_SHORT).show();
	                    		}
		                    	dialog.dismiss();
		                    }
		                    else{
		                    	Toast.makeText(getBaseContext(), "Please input value!", Toast.LENGTH_SHORT).show();
		                    }
		                    	
		                }
		              });
		                dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		                    public void onClick(DialogInterface dialog, int whichButton) {
		                        dialog.dismiss();
		                    }
		                });
		                AlertDialog alert0 = dialog.create();
		    			return alert0;
		           
			case DIALOG_RESULT_AUTHO:
				dialog.setTitle(" Notice! ");
				dialog.setMessage(dialogmessage);
				dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
				AlertDialog alertresult = dialog.create();
				return alertresult;
				
				
			 case DIALOG_WAITTING: {
	                ProgressDialog dialogwait = new ProgressDialog(this);
	                dialogwait.setMessage(dialogmessage);
	                dialogwait.setIndeterminate(true);
	                dialogwait.setCancelable(true);
	                return dialogwait;
	            }
			}
           return super.onCreateDialog(id);
	}
	
	
	
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		progress.setVisibility(View.GONE);
		showstatus.setVisibility(View.INVISIBLE);
	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		ExportQuestionToCsvFile.this.finish();
	}
 	private void writeFile(String path, ArrayList<String> data) {
		String[] temp = path.split("/");
		String fileName = temp[temp.length-1];
		String tempPath = path.replace(fileName, "");
		File file = new File(tempPath);
		
		long totalSize = data.size();
		long currentPos = 0;
		
		if(!file.exists()){
			if(file.mkdirs()){
				Log.e("cannc", "Success create path - " + path);
			}
			else{
				Log.e("cannc", "Error: Cann't create path - " + tempPath);
			}
		}
		if(file.exists()){
			try {
				Log.e("cannc", "Success Backup - " + path);
				FileWriter out = new FileWriter(path, false);
				for(int i = 0; i < data.size(); i++) {
					out.write(data.get(i));
					out.write("\n");
					// chay progress tai vi tri current
					currentPos =i;
						progress.setProgress((int)((currentPos*100)/totalSize));
				}
				
				out.close();
			}
			catch (IOException e)
			{
				Log.e("cannc", "Error: cann't write file backup - " + path);
			}
		}
	}
	
 	public void Exportdata(){
 		
 		filename = et_Enterfilename.getText().toString().trim();
			if(filename.equals("")) {
				dialogmessage = "Please input file name";
				showDialog(0);
			}
			else{
				filepath = path + filename+".csv";
					data.addAll(questionData.getQuestionExport());
				}
				System.out.println("data.size()   "+data.size());
				new DoBackgroundImportFile().execute("abc");
 	}
	
	
	 @Override
		protected Dialog onCreateDialog(int id) {
			// TODO Auto-generated method stub
			//return super.onCreateDialog(id);
			   AlertDialog.Builder dialog =new AlertDialog.Builder(this);
			switch (id) {
			
			case 0:
				dialog.setTitle(" Notice! ");
				dialog.setMessage(dialogmessage);
				dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
				AlertDialog alert1 = dialog.create();
				alert1.show();
				break;
			}
			return null;
	   }//end dialog
	 
	 private class DoBackgroundImportFile extends AsyncTask<String, Integer, Long>{

			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				progress.setVisibility(View.VISIBLE);
				btnExport.setVisibility(View.INVISIBLE);
				progress.setProgress(myprogress);
				showstatus.setVisibility(View.VISIBLE);
				if(syncDocs.isAuthorize() == true && isCheksync == true)
				{
					showstatus.setVisibility(View.INVISIBLE);
					progress.setVisibility(View.INVISIBLE);
					dialogmessage = "Please wait while synchronizing...";
					showDialog(DIALOG_WAITTING);
				}
				else
				{
					showstatus.setVisibility(View.VISIBLE);
				}
				showstatus.setText("Loading...");
				
				
				
			}

			@Override
			protected void onPostExecute(Long result) {
				// TODO Auto-generated method stub
				//super.onPostExecute(result);
				Log.d("Import file","finished import");
				progress.setProgress(100);
				progress.setVisibility(View.GONE);
				btnExport.setVisibility(View.VISIBLE);
				data.clear();
				if(syncDocs.isAuthorize() == true && isCheksync == true)
				{
					
					AsyncTask<String, String, String> downloadFile = new AsyncTask<String, String, String>(){

						@Override
						protected void onPreExecute() {
							// TODO Auto-generated method stub
							super.onPreExecute();
						}

						@Override
						protected void onPostExecute(String result) {
							// TODO Auto-generated method stub
							super.onPostExecute(result);
							dismissDialog(DIALOG_WAITTING);
							showstatus.setText(" Export successful! ");
						}

						@Override
						protected String doInBackground(String... params) {
							try {
								// start to update data to google doc
								syncDocs.UpdateToGoogleDocs(new File(filepath), filename);
								showstatus.setVisibility(View.VISIBLE);
							} catch (Exception e) {
							}
							return "";
						}
						
					}.execute("");
				}				
				else{
					showstatus.setText(" Export successful! ");
				}
			}

			@Override
			protected void onProgressUpdate(Integer... values) {
				// TODO Auto-generated method stub
				Log.d("ANDRp_ASYN",""+values[0]);
				progress.setProgress(values[0]);
			}

			@Override
			protected Long doInBackground(String... params) {
				// TODO Auto-generated method stub
				try {
					writeFile(filepath, data);
				} catch (Exception e) {
					System.out.println(e);
				}
				return null;
			}


		}
	 
	 private static final String RELOGIN = "Login with another account";
		
	   @Override
		public boolean onCreateOptionsMenu(Menu menu) {
			// TODO Auto-generated method stub
			super.onCreateOptionsMenu(menu);
			CreateMenu(menu);
			return true;
		}

		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
			// TODO Auto-generated method stub
			super.onOptionsItemSelected(item);
			return MenuChoice(item);
		}

		private void CreateMenu(Menu menu)
	    {
	    	menu.add(0, 0, 0, RELOGIN);
	    }
		
	   private boolean MenuChoice(MenuItem item)
	   {
		switch (item.getItemId()) {
		case 0:
			showDialog(DIALOG_AUTHO);
			return true;
		}
		return false;
		   
	   }   

}
